package com.pb.camera.broadcast;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import com.pb.camera.jph.activity.SettingCameraWifiActivity;
import com.pb.camera.utils.Assert;

/**
 * Created by Liu Fei on 2016/4/12 0012.
 * 设置wifi的代理,用来完成 wifi的设置等
 */
public class WifiSettingProxy implements WifiBroadcastReceiver.WifiStatuInterface {
    private Context context;
    private ScanResult mSelectedScanResult;

    private boolean isReseting = false;
    private boolean mIsJumped = false;
    private WifiBroadcastReceiver mBroadcastReceiver;
    private Intent intent;

    public WifiSettingProxy(Context context, ScanResult scanResult) {
        this.context = context;
        this.mSelectedScanResult = scanResult;
        init();
    }

    private void init() {
        mBroadcastReceiver = new WifiBroadcastReceiver();
        mBroadcastReceiver.setInterface(this);
        IntentFilter intentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        context.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public void onConnect(String ssid) {
        if (mSelectedScanResult == null)
            return;
        String targetSSID = "\"" + mSelectedScanResult.SSID + "\"";
        //没有正确连接到指定wifi，就去让用户手动去设置
        if (isReseting && !ssid.equals(targetSSID) && !mIsJumped) {
            Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
            context.startActivity(wifiSettingsIntent);
            mIsJumped = true;
        } else if (ssid.equals(targetSSID) && intent != null) {
            context.startActivity(intent);
        }
    }

    @Override
    public void onDisconnect() {
        isReseting = true;
    }

    public void setIntent(Intent intent) {
        this.intent = intent;
    }

    public void finishProxy() {
        context.unregisterReceiver(mBroadcastReceiver);
    }
}
